let ScheduleService = require('./ScheduleService');
var schedule = require("node-schedule");
let Mongodb = require('../../database/mongodb');
var request = require('request');
var CICI = require('../../routes/message/cici');

class DeployCheck extends ScheduleService {
  initRule () {
    // 20秒钟执行一次
    this.rule.second = [1,21,41];
  }

  runTask (params) {
    let curSeconde = new Date().getTime()
    console.log(curSeconde + '检查服务是否启动')
    let that = this
    Mongodb.find('deployhistory', { state: 0 }, {}, {}, function(err, docs){      
      if (docs && (docs.length > 0)) {
        console.log(curSeconde + '数量：' + docs.length)
        docs.forEach(server => {          
          request.get({
            url: server.checkUrl,
            timeout: 3000
          }, (error, response, body) => {
            if (!error && response.statusCode == 200) {
              console.log(curSeconde + '服务已启动')
              Mongodb.update('deployhistory', { '_id': server._id }, { 'state': 1 }, () => {
                Mongodb.findOne('subscription', { 'type': 0 }, function(err, sub){
                  if (!err && sub) {
                    console.log(curSeconde + '发送消息')
                    sendMessage(sub.userId, `${server.serverName}升级完成`)
                  } else {
                    console.log(err)
                  }
                })
              })
            } else {
              console.log(curSeconde + '服务还未启动')
              console.log(error)
              console.log(response)
            }
          })
        })
      } else {
        console.log(curSeconde + '无启动服务退出调度')
        that.cancel()
      }
    })
  }
}

function sendMessage (emails, content) {
  for (let i = 0; i < emails.length; i++) {
      CICI.remindMess(emails[i], content, 'https://test/works/#/dashboard/board', () => {});
  }
}

module.exports = new DeployCheck()
